/*
 *    This file is part of SSHTunneler.
 *
 *    Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
 *
 *    SSHTunneler is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    SSHTunneler is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with SSHTunneler.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package sshtunneler.packager.gui.helpers;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

public class JTableButtonMouseListener implements MouseListener {

	private JTable associated_table;

	private void forward_event(MouseEvent e) {
		TableColumnModel columnModel = this.associated_table.getColumnModel();
		int column = columnModel.getColumnIndexAtX(e.getX());
		int row = e.getY() / this.associated_table.getRowHeight();
		Object value;
		JButton button;
		MouseEvent buttonEvent;

		if (row >= this.associated_table.getRowCount() || row < 0
				|| column >= this.associated_table.getColumnCount()
				|| column < 0) {
			return;
		}
		value = this.associated_table.getValueAt(row, column);

		if (!(value instanceof JButton)) {
			return;
		}
		button = (JButton) value;

		buttonEvent = SwingUtilities.convertMouseEvent(this.associated_table,
				e, button);
		button.dispatchEvent(buttonEvent);
		this.associated_table.repaint();
	}

	public JTableButtonMouseListener(JTable table) {
		this.associated_table = table;
	}

	public void mouseClicked(MouseEvent e) {
		this.forward_event(e);
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
		this.forward_event(e);
	}

	public void mouseReleased(MouseEvent e) {
		this.forward_event(e);
	}
}
